package com.ncloud.system.controller;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ncloud.auth.config.Constant;
import com.ncloud.auth.service.AuthService;
import com.ncloud.common.body.Result;
import com.ncloud.common.utils.ResultUtil;
import com.ncloud.system.entity.User;
import com.ncloud.system.service.FileService;
import com.ncloud.system.service.UserService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

@Api(value = "自动化运维用户管理", description = "用户管理", tags = "用户管理",
	basePath="/",consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
@RestController
public class UserController {
	
	@Autowired
	private UserService userService;
	@Autowired
	private AuthService authService;
	@Autowired
	private FileService fileService;
	
	@GetMapping(value = "/users")
	@ApiOperation(value="list users", notes="根据企业和帐号组查询用户列表")
	@ApiImplicitParams({
		@ApiImplicitParam(paramType="header",name = "X-CSRF-TOKEN", value = "认证token", required = true, dataType = "String" ),
        @ApiImplicitParam(name = "companyId", value = "企业编码", required = false, dataType = "Long" ),
        @ApiImplicitParam(name = "roleId", value = "角色编码", required = false, dataType = "Long" ),
        @ApiImplicitParam(name = "departId", value = "用户组", required = false, dataType = "Long" ),
        @ApiImplicitParam(name = "userName", value = "账号", required = false, dataType = "String" ),
        @ApiImplicitParam(name = "pageSize", value = "每页数量", required = false, dataType = "Long" ),
        @ApiImplicitParam(name = "pageNum", value = "页数", required = false, dataType = "Long" )
	})
    public Result<?> getUsers(@RequestParam(required=false) Long companyId,@RequestParam(required=false) Long departId,
    		@RequestParam(required=false) Long roleId,@RequestParam(required=false) String userName,@RequestParam(required=false) Long pageSize,
    		@RequestParam(required=false) Long pageNum, HttpServletRequest request)	throws Exception {
		String userId = (String) request.getAttribute("userID");
		User user = userService.findByUserId(Long.parseLong(userId));
		if("1".equals(user.getSuperman())){
			if(companyId!=null && companyId.intValue()<=0) companyId = null;
		}else{
			companyId = user.getCompanyId();
		}
		JSONObject json = new JSONObject();
		json.put("companyId", companyId);
		json.put("roleId", (roleId == null || roleId.intValue()<=0)?null:roleId);
		json.put("departId", (departId == null || departId.intValue()<=0)?null:departId);
		json.put("account", userName);
		if(pageSize != null && pageNum != null){
			json.put("pageSize", pageSize);
			json.put("pageNum", pageNum);
		}
		
		Object object = userService.getUsers(json);
		return ResultUtil.success(object);
	}
    
	@GetMapping(value = "/user")
	@ApiOperation(value="user-info", notes="获取用户信息")
	@ApiImplicitParams({
		@ApiImplicitParam(paramType="header",name = "X-CSRF-TOKEN", value = "认证token", required = true, dataType = "String" )
	})
    public Result<?> getUser(HttpServletRequest request) throws Exception {
		String userId = (String) request.getAttribute("userID");
		User user = userService.findByUserId(Long.parseLong(userId));
		return ResultUtil.success(JSON.parseObject(JSON.toJSONString(user)));
	}
	
	@GetMapping(value = "/user/{userId}")
	@ApiOperation(value="user-info", notes="获取指定用户信息")
	@ApiImplicitParams({
		@ApiImplicitParam(paramType="header",name = "X-CSRF-TOKEN", value = "认证token", required = true, dataType = "String" ),
		@ApiImplicitParam(paramType="path",name = "userId", value = "用户编码", required = true, dataType = "Long" )
	})
    public Result<?> getUserByUserId(@PathVariable Long userId, HttpServletRequest request) throws Exception {
		User user = userService.findByUserId(userId);
		return ResultUtil.success(JSON.parseObject(JSON.toJSONString(user)));
	}
	
	@PostMapping("/user")
	@ApiOperation(value="create user", notes="用户创建：根据输入的用户信息生成用户")
    @ApiImplicitParams({
    	@ApiImplicitParam(paramType="header",name = "X-CSRF-TOKEN", value = "认证token", required = true, dataType = "String" ),
        @ApiImplicitParam(name = "user", value = "用户详细信息", required = true, dataType = "User") 
    })
    public Result<?> addUser(@RequestBody JSONObject json, HttpServletRequest request) throws Exception{
    	String operId = (String) request.getAttribute("userID");
    	json.put("operId", operId);
		userService.addUser(json);
		return ResultUtil.success();
    }
	
	@ApiOperation(value="update user", notes="用户修改：根据用户主键对用户信息进行修改")
    @ApiImplicitParams({
    	@ApiImplicitParam(paramType="header",name = "X-CSRF-TOKEN", value = "认证token", required = true, dataType = "String" ),
        @ApiImplicitParam(name = "user", value = "用户详细信息", required = true, dataType = "User")    
    })
	@PutMapping("/user")
    public Result<?> updateUser(@RequestBody JSONObject json, HttpServletRequest request) throws Exception{
		String operId = (String) request.getAttribute("userID");
    	json.put("operId", operId);
    	userService.updateUser(json);
    	return ResultUtil.success();
    }
    
	@PutMapping("/user/{userId}/lock")
	@ApiOperation(value="lock user", notes="锁定用户")
	@ApiImplicitParams({
		@ApiImplicitParam(paramType="header",name = "X-CSRF-TOKEN", value = "认证token", required = true, dataType = "String" ),
        @ApiImplicitParam(paramType="path",name = "userId", value = "用户编码", required = true, dataType = "Long" )
	})
    public Result<?> lockUser(@PathVariable Long userId) throws Exception{
		userService.lockUser(userId);
    	return ResultUtil.success();
    }
	
	@PutMapping("/user/{userId}/unlock")
	@ApiOperation(value="unlock user", notes="解锁用户")
	@ApiImplicitParams({
		@ApiImplicitParam(paramType="header",name = "X-CSRF-TOKEN", value = "认证token", required = true, dataType = "String" ),
        @ApiImplicitParam(paramType="path",name = "userId", value = "用户编码", required = true, dataType = "Long" )
	})
    public Result<?> unlockUser(@PathVariable Long userId) throws Exception{
		userService.unLockUser(userId);
    	return ResultUtil.success();
    }
	
	@DeleteMapping("/user/{userId}")
	@ApiOperation(value="delete user", notes="删除用户")
	@ApiImplicitParams({
		@ApiImplicitParam(paramType="header",name = "X-CSRF-TOKEN", value = "认证token", required = true, dataType = "String" ),
        @ApiImplicitParam(paramType="path",name = "userId", value = "用户编码", required = true, dataType = "Long" )
	})
    public Result<?> deleteUser(@PathVariable Long userId,HttpServletRequest request) throws Exception{
		userService.deleteUser(userId);
    	return ResultUtil.success();
    }
	
	@ApiOperation(value="判断用户是否存在", notes="输入用户校验是否已经存在")
	@GetMapping("/user/isExists")
	@ApiImplicitParams({
		@ApiImplicitParam(paramType="header",name = "X-CSRF-TOKEN", value = "认证token", required = true, dataType = "String" ),
        @ApiImplicitParam(name = "userName", value = "账号", required = true, dataType = "String" )
	})
	public Result<?> isExists(@RequestParam String userName,HttpServletRequest request) throws Exception{
		boolean flag = userService.isExists(userName);
		return ResultUtil.success(flag);
	}
	
	@ApiOperation(value="校验密码是否正确", notes="根据密码校验是否正确")
	@ApiImplicitParams({
		@ApiImplicitParam(paramType="header",name = "X-CSRF-TOKEN", value = "认证token", required = true, dataType = "String" ),
        @ApiImplicitParam(name = "password", value = "密码", required = true, dataType = "JSONObject" )
	})
	@PostMapping("/user/checkPassword")
	public Result<?> checkPassword(@RequestBody JSONObject json,HttpServletRequest request) throws Exception{
		String userId = (String) request.getAttribute("userID");
		userService.checkPassword(Long.parseLong(userId), json.getString("password"));
		return ResultUtil.success();
	}
	
	@ApiOperation(value="重置密码", notes="根据认证码进行校验之后进行密码重置")
	@ApiImplicitParams({
		@ApiImplicitParam(paramType="header",name = "X-CSRF-TOKEN", value = "认证token", required = true, dataType = "String" ),
        @ApiImplicitParam(name = "json", value = "用户编码/旧密码和新密码", required = true, dataType = "JSONObject" )
	})
	@PutMapping("/user/resetPassword")
	public Result<?> resetPassword(@RequestBody JSONObject json,HttpServletRequest request) throws Exception{
		String userId = (String) request.getAttribute("userID");
		String oldPasswd = json.getString("oldPassword");
		String newPasswd = json.getString("newPassword");
		userService.checkPassword(Long.parseLong(userId), oldPasswd);
		userService.resetPassword(Long.parseLong(userId), newPasswd);
		String token = request.getHeader(Constant.HEAD_TOKEN);
    	authService.destroy(token);
		return ResultUtil.success();
	}
	
	@ApiOperation(value="重置密码", notes="管理员给用户充值密码")
	@ApiImplicitParams({
		@ApiImplicitParam(paramType="header",name = "X-CSRF-TOKEN", value = "认证token", required = true, dataType = "String" ),
		@ApiImplicitParam(paramType="path", name = "userId", value = "用户编码", required = true, dataType = "Long" ),
        @ApiImplicitParam(paramType="form", name = "newPassword", value = "新密码", required = true, dataType = "String" )
	})
	@PutMapping("/user/{userId}/resetPassword")
	public Result<?> resetUserPassword(@PathVariable Long userId, @RequestParam String newPassword,HttpServletRequest request) throws Exception{
		String operId = (String) request.getAttribute("userID");
		// 判断登陆用户是否有管理角色
		userService.resetPassword(userId, newPassword);
		String token = request.getHeader(Constant.HEAD_TOKEN);
    	authService.destroy(token);
		return ResultUtil.success();
	}
	
	@ApiOperation(value="上传用户头像", notes="上传用户头像")
	@ApiImplicitParams({
		@ApiImplicitParam(paramType="header",name = "X-CSRF-TOKEN", value = "认证token", required = true, dataType = "String" ),
        @ApiImplicitParam(name = "file", value = "头像文件", required = true, dataType = "MultipartFile" )
	})
	@PutMapping("/user/head/upload")
	public Result<?> headUpload(HttpServletRequest request, @RequestParam("file") MultipartFile file) throws Exception{
		String userId = (String) request.getAttribute("userID");
		String filePath = fileService.headUpload(file);
		userService.setUserHead(Long.parseLong(userId), filePath);
		return ResultUtil.success();
	}
	
}
